package com.sandama.bbs.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.sandama.bbs.R;
import com.sandama.bbs.common.Constants;
import com.sandama.bbs.model.Game;
import com.sandama.bbs.model.Group;
import com.sandama.bbs.model.User;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author:TongxiJi
 * Function:
 * Create Date:十月10,2015
 */
public class LoadingActivity extends AppCompatActivity {
    public static final String BBS_HOME_PAGE_DATA = "BBSHomePageData";

    @Bind(R.id.tv_progress)
    TextView tvProgress;
    @Bind(R.id.pb_main)
    ProgressBar pbMain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        ButterKnife.bind(this);

        listAsyncTask.execute((Void[]) null);
    }

    AsyncTask<Void, Integer, List<Group>> listAsyncTask = new AsyncTask<Void, Integer, List<Group>>() {
        @Override
        protected void onPreExecute() {
            tvProgress.setText("正在加载数据");
        }

        @Override
        protected List<Group> doInBackground(Void... voids) {
//            long start = System.currentTimeMillis();

            List<Group> groups = new ArrayList<Group>();

            Document doc = null;
            try {
                doc = Jsoup.connect(Constants.BBS_URL).userAgent(Constants.PC_USER_AGENT).timeout(10000).get();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

//            long end = System.currentTimeMillis();
//            Log.i("JITX", "时间消耗：" + (end - start) / 1000.000);

            Elements groupElements = doc.select("div.bm.bmw.flg.cl");

            publishProgress(0, groupElements.size());

            for (Element element : groupElements) {
                //进度条
                publishProgress(groupElements.indexOf(element) + 1, groupElements.size());


                //分区 分区版主
                Element elmntHd = element.select("div.bm_h.cl").first();

                Group group = new Group();
                group.setName(elmntHd.select("h2").select("a").first().ownText().replace("()", ""));
                group.setSubGroupUrl(Constants.MAIN_URL + "/" + elmntHd.select("h2").select("a").first().attr("href"));

//            System.out.println(group.toString());

                List<User> admins = group.getAdmins();
                Elements masters = elmntHd.select("span.y").select("a");
                for (Element master : masters) {
                    User user = new User();
                    user.setName(master.text());
                    user.setSpaceUrl(Constants.MAIN_URL + "/" + master.attr("href"));
                    admins.add(user);
//                System.out.println(user.toString());
                }

                //游戏
                Elements elementsGames = element.select("table.fl_tb").select("td.fl_g");
                for (Element elementGame : elementsGames) {
                    Game game = new Game();

                    //logo
                    Elements elementsImg = elementGame.select("div.fl_icn_g").select("img");
                    String gameLogoUrl = "";
                    if (elementsImg.hasAttr("src")) {
                        gameLogoUrl = elementGame.select("div.fl_icn_g").select("img").attr("src");
                    } else if (elementsImg.hasAttr("file")) {
                        gameLogoUrl = elementGame.select("div.fl_icn_g").select("img").attr("file");
                    }
                    //url
                    String detailUrl = Constants.MAIN_URL + "/" + elementGame.select("div.fl_icn_g").select("a").attr("href");
                    //name
                    String gameName = elementGame.select("dt").select("a").text();
                    //回帖数
                    String postCount = elementGame.select("dt").select("em").text();

                    //主题
                    String hotTopicUrls = elementGame.select("dd[style=color:#666;]").html().replace("||", "<br />").replace("http", getString(R.string.my_web_custom_scheme));

                    game.setLogoUrl(gameLogoUrl);
                    game.setName(gameName);
                    game.setDetailUrl(detailUrl);
                    game.setPostCount(postCount);
                    game.setHotTopics(hotTopicUrls);

                    group.getGames().add(game);
//                System.out.println(game.toString());
                }

                groups.add(group);
            }
            return groups;
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            pbMain.setMax(values[1]);
            pbMain.setProgress(values[0]);
            tvProgress.setText(String.format("%s/%s", values[0], values[1]));
        }

        @Override
        protected void onPostExecute(List<Group> groups) {
            tvProgress.setText(groups != null ? "加载数据完成" : "数据加载失败");
//            tvProgress.setVisibility(View.INVISIBLE);
//            pbMain.setVisibility(tvProgress.getVisibility());
            if (groups != null) {
                Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
                intent.putExtra(BBS_HOME_PAGE_DATA, (ArrayList<Group>) groups);
                startActivity(intent);
                finish();
            }
        }
    };
}
